#include "Input.h"
#include "Constants.h"
#include <SDL/SDL.h>
#include <iostream>
using namespace std;

Input::Input()
{
	for (int i=0; i<321; i++)
	{
		key[i] = false;
	}
}

void Input::addKeyListener(KeyListener * listener)
{
	keyListeners.push_back(listener);
}

void Input::addMouseListener(MouseListener * listener)
{
	mouseListeners.push_back(listener);
}

Input::~Input()
{
}

bool Input::events()
{
	SDL_Event event;
	if(SDL_PollEvent(&event))
	{
		switch(event.type)
		{
			case SDL_KEYDOWN : 
				key[event.key.keysym.sym ] = true;
				handleKeyEvent(); 
				break;
			case SDL_KEYUP :
				key[event.key.keysym.sym ] = false;
				handleKeyEvent();
				break;
			case SDL_QUIT :
				return false;
				break;
			case SDL_MOUSEBUTTONDOWN :
				handleMouseEvent(&event);
				break;
			case SDL_MOUSEMOTION :
				handleMouseEvent(&event);
				break;
		}
	}
	return true;	
}

void Input::handleMouseEvent(SDL_Event * event)
{
	for(int i=0; (unsigned)i < mouseListeners.size(); i++)
	{
		mouseListeners[i]->handleEvent(event);
	}
}

void Input::handleKeyEvent()
{
	for(int i=0; (unsigned)i < keyListeners.size(); i++)
	{
		keyListeners[i]->handleEvent(key);
	}
	
	if(key[SDLK_ESCAPE])
	{
		cout << "Escape hit, quitting";
		throw "bail";
	}
}
